/**
 * 
 */
package com.hj.service;

import java.lang.reflect.Field;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * @author huangj 2010-1-1
 * @sea http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/aop.html#aop-ataspectj
 */
@Aspect
public class HibernateAspect {
	private static final String UPDATOR = "lastModifiedBy";
	private static final String UPDATEDDATE = "lastModifiedDate";
	private static final String CREATOR = "createdBy";
	private static final String CREATEDDATE = "createdDate";
	//execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
	//"execution(* com.hj.dao.*Manager.save*(..))"
	@Pointcut("execution(* com.hj.dao.*Manager.save*(..))")
	public void saveOrUpdate() {}
	//&& @annotation(org.springframework.transaction.annotation.Transactional)
	//org.springframework.stereotype.Repository
	//org.springframework.transaction.annotation.Transactional
	@Around("saveOrUpdate() && target(tar) && args(entity)")
	public void aroundSave(ProceedingJoinPoint point, Object tar, Object entity) throws Throwable {
		// logger.info(tar.toString());
		String idValue = "";
		Date now = new Date();
		String userCd = SpringSecurityUtils.getCurrentUserName();
		// 如果当然登录用户用空，取Admin
		if (StringUtils.isEmpty(userCd)) {
			userCd = "admin";
		}
		if (StringUtils.isEmpty(idValue)) {
			// 创建时间
			Date createdDate = (Date) PropertyUtils.getProperty(entity, CREATEDDATE);
			if (createdDate == null) {
				BeanUtils.setProperty(entity, CREATEDDATE, now);
			}
			// 创建人
			String creator = getValue(entity, CREATOR);
			if (StringUtils.isEmpty(creator)) {
				BeanUtils.setProperty(entity, CREATOR, userCd);
			}
		}
		setValue(entity, UPDATEDDATE, now); // 更新时间
		setValue(entity, UPDATOR, userCd);// 更新人
		point.proceed();
	}

	private void setValue(Object entity, String fieldName, Object fieldValue) {
		try {
			BeanUtils.setProperty(entity, fieldName, fieldValue);
		} catch (Exception e) {
		}
	}
	
	private String getValue(Object entity, String fieldName) {
		String fieldValue=null;
		try {
			fieldValue=BeanUtils.getProperty(entity, fieldName);
		} catch (Exception e) {
		}
		return fieldValue;
	}
	
	private boolean isExistsProperty(Object entity, String propertyName) {
		boolean flag = false;
		Field[] fields = entity.getClass().getFields();
		for (Field field : fields) {
			if (field.getName().equals(propertyName)) {
				flag = true;
			}
		}
		return flag;
	}
}
